import type { AxiosRequestConfig } from 'axios'
import axios from 'axios'

// 存储待处理的请求
const pendingMap = new Map<string, () => void>()

// 获取请求的唯一键
const getRequestKey = (config: AxiosRequestConfig) => {
    const { url, method, params, data } = config
    return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&')
}

// 添加请求
export function add(config: AxiosRequestConfig) {
    const key = getRequestKey(config)
    config.cancelToken = new axios.CancelToken(cancel => {
        if (!pendingMap.has(key)) {
            pendingMap.set(key, cancel)
        }
    })
}

// 移除请求
export function remove(config: AxiosRequestConfig) {
    const key = getRequestKey(config)
    if (pendingMap.has(key)) {
        const cancel = pendingMap.get(key)
        cancel && cancel()
        pendingMap.delete(key)
    }
}

// 清除所有请求
export function clear() {
    pendingMap.forEach(cancel => {
        cancel && cancel()
    })
    pendingMap.clear()
}
